package com.cbgolf.oa.activity.coupon;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.cbgolf.oa.R;
import com.cbgolf.oa.base.BaseActivity;
import com.cbgolf.oa.net.NetCallBack;
import com.cbgolf.oa.net.NetUtils;
import com.cbgolf.oa.net.Web;
import com.cbgolf.oa.net.WebAPI;
import com.cbgolf.oa.user.UserData;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.DensityUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.widget.AutoResizeTextView;
import com.cbgolf.oa.widget.datechoose.DateChooseWheelViewDialog;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * @author Created by lq  on 2017/9/4.
 */

public class CouponCreateActivity extends BaseActivity {

  //top
  @ViewInject(R.id.topBack_ll)
  private View topBack;
  @ViewInject(R.id.title_tv)
  private TextView topTitle;
  //body
  @ViewInject(R.id.a_coupon_create_parkname_et)
  private EditText parkNameEt;
  @ViewInject(R.id.a_coupon_create_begin_time_ll)
  private View startTimeView;
  @ViewInject(R.id.a_coupon_create_begin_time_tv)
  private TextView startTimeTv;
  @ViewInject(R.id.a_coupon_create_over_time_ll)
  private View overTimeView;
  @ViewInject(R.id.a_coupon_create_over_time_tv)
  private TextView overTimeTv;
  @ViewInject(R.id.a_coupon_create_money_num_et)
  private EditText moneyNumEt;
  @ViewInject(R.id.a_coupon_create_limit_et)
  private EditText moneyLimitEt;
  @ViewInject(R.id.a_coupon_create_push_count_et)
  private EditText pushCountEt;
  @ViewInject(R.id.a_coupon_create_limit_count_et)
  private EditText limitCountEt;
  //
  @ViewInject(R.id.a_coupon_create_money_num_tv)
  private TextView moneyNumTv;
  @ViewInject(R.id.a_coupon_create_limit_tv)
  private TextView moneyLimitTv;
  @ViewInject(R.id.a_coupon_create_push_count_tv)
  private TextView pushCountTv;
  @ViewInject(R.id.a_coupon_create_limit_count_tv)
  private TextView limitCountTv;

  //
  @ViewInject(R.id.a_coupon_create_num_tv)
  private AutoResizeTextView numTv;
  @ViewInject(R.id.a_coupon_create_type_tv)
  private TextView typeTv;
  @ViewInject(R.id.a_coupon_create_name_tv)
  private TextView parkNameTv;
  @ViewInject(R.id.a_coupon_create_lowest_tv)
  private TextView lowestTv;
  @ViewInject(R.id.a_coupon_create_duration_tv)
  private TextView usedTimeTv;
  //submit
  @ViewInject(R.id.a_coupon_create_tv)
  private TextView createTv;

  private long startTime = -1;
  private long overTime = -1;

  private String parValue;
  private String lowestNum;
  private String pushCount;
  private String limitCount;


  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.a_coupon_create);
  }

  @Override
  protected void findViews() {
    x.view().inject(this);
  }

  @Override
  protected void setViews() {
    topTitle.setText("创建优惠券");
    String parkName = UserData.getUser() == null ? "" : UserData.getUser().getCourseName();
    parkNameEt.setText(parkName);
    parkNameEt.setEnabled(false);
    typeTv.setText("球场券");
    parkNameTv.setText(parkName);

  }

  @Override
  protected void setListener() {
    topBack.setOnClickListener(v -> finish());
    startTimeView.setOnClickListener(v -> {
      DateChooseWheelViewDialog startDateChooseDialog
          = new DateChooseWheelViewDialog(context,
          (time, longTimeChecked) -> {
            if (!Util.isNull(time)) {
              StringBuilder builder = new StringBuilder();
              try {
                startTime = Long.parseLong(DateUtil.dateToStampyMdHm(time));
                startTimeTv.setText(
                    DateUtil.stampToDate(String.valueOf(startTime), DateUtil.formatWithbias));
                builder.append("2.有效期")
                    .append(DateUtil.stampToDateyMd2(String.valueOf(startTime)))
                    .append((-1 == overTime ? ""
                        : DateUtil.stampToDateyMd2(String.valueOf(overTime))));
                ViewUtils.setText(usedTimeTv, builder.toString());
              } catch (Exception e) {
                startTime = -1;
                builder.append("2.有效期")
                    .append((time.split(" ")[0] + "-"))
                    .append(
                        (-1 == overTime ? "" : DateUtil.stampToDateyMd2(String.valueOf(overTime))));
                ViewUtils.setText(usedTimeTv, builder.toString());
              }
            }
          });
      startDateChooseDialog.setDateDialogTitle("生效时间");
      startDateChooseDialog.showDateChooseDialog();
    });
    overTimeView.setOnClickListener(v -> {
      DateChooseWheelViewDialog startDateChooseDialog
          = new DateChooseWheelViewDialog(context,
          (time, longTimeChecked) -> {
            if (!Util.isNull(time)) {
              StringBuilder builder = new StringBuilder();
              try {
                overTime = Long.parseLong(DateUtil.dateToStampyMdHm(time));
                overTimeTv.setText(
                    DateUtil.stampToDate(String.valueOf(overTime), DateUtil.formatWithbias));
                builder.append("2.有效期")
                    .append((-1 == startTime ? ""
                        : DateUtil.stampToDateyMd2(String.valueOf(startTime))))
                    .append("-" + DateUtil.stampToDateyMd2(String.valueOf(overTime)));
                ViewUtils.setText(usedTimeTv, builder.toString());
              } catch (Exception e) {
                overTime = -1;
                builder.append("2.有效期")
                    .append((-1 == startTime ? ""
                        : DateUtil.stampToDateyMd2(String.valueOf(startTime))))
                    .append(("-" + time.split(" ")[0]));
                ViewUtils.setText(usedTimeTv, builder.toString());
              }
            }
          });
      startDateChooseDialog.setDateDialogTitle("失效时间");
      startDateChooseDialog.showDateChooseDialog();
    });
    moneyNumTv.setOnClickListener(v -> {
      moneyNumTv.setVisibility(View.GONE);
      moneyNumEt.setVisibility(View.VISIBLE);
      requestFocus(moneyNumEt);
      Util.showInput(moneyNumEt);
    });
    moneyNumEt.setOnFocusChangeListener((v, hasFocus) -> {
      if (!hasFocus) {
        String num = moneyNumEt.getText().toString().trim();
        moneyNumTv.setVisibility(View.VISIBLE);
        moneyNumEt.setVisibility(View.GONE);
        ViewUtils.setText(moneyNumTv, !Util.isNull(num) ? (num + "元") : "");
        ViewUtils.setText(numTv, num);
        numTv.resetSize(DensityUtil.sp2px(context, 38));
      }
    });
    moneyLimitTv.setOnClickListener(v -> {
      moneyLimitTv.setVisibility(View.GONE);
      moneyLimitEt.setVisibility(View.VISIBLE);
      requestFocus(moneyLimitEt);
      Util.showInput(moneyLimitEt);
    });
    moneyLimitEt.setOnFocusChangeListener((v, hasFocus) -> {
      if (!hasFocus) {
        String num = moneyLimitEt.getText().toString().trim();
        moneyLimitTv.setVisibility(View.VISIBLE);
        moneyLimitEt.setVisibility(View.GONE);
        if (!Util.isNull(num)) {
          moneyLimitTv.setText(("订场满" + num + "元可使用"));
          lowestTv.setText(("1.订场满" + num + "元可使用"));
        } else {
          moneyLimitTv.setText("");
          lowestTv.setText("1.订场满0元可使用");
        }
      }
    });
    pushCountTv.setOnClickListener(v -> {
      pushCountTv.setVisibility(View.GONE);
      pushCountEt.setVisibility(View.VISIBLE);
      requestFocus(pushCountEt);
      Util.showInput(pushCountEt);
    });
    pushCountEt.setOnFocusChangeListener((v, hasFocus) -> {
      if (!hasFocus) {
        String num = pushCountEt.getText().toString().trim();
        pushCountTv.setVisibility(View.VISIBLE);
        pushCountEt.setVisibility(View.GONE);
        if (!Util.isNull(num)) {
          pushCountTv.setText(("共" + num + "张"));
        } else {
          pushCountTv.setText("");
        }
      }
    });
    limitCountTv.setOnClickListener(v -> {
      limitCountTv.setVisibility(View.GONE);
      limitCountEt.setVisibility(View.VISIBLE);
      requestFocus(limitCountEt);
      Util.showInput(limitCountEt);
    });
    limitCountEt.setOnFocusChangeListener((v, hasFocus) -> {
      if (!hasFocus) {
        String num = limitCountEt.getText().toString().trim();
        limitCountTv.setVisibility(View.VISIBLE);
        limitCountEt.setVisibility(View.GONE);
        if (!Util.isNull(num)) {
          limitCountTv.setText(("每人限领" + num + "张"));
        } else {
          limitCountTv.setText("");
        }
      }
    });
    createTv.setOnClickListener(v -> {
      clearFoucs();
      checkInfo();
    });
  }


  private void clearFoucs() {
    moneyNumEt.clearFocus();
    moneyLimitEt.clearFocus();
    pushCountEt.clearFocus();
    limitCountEt.clearFocus();
  }

  private void checkInfo() {
    if (!Util.isNetWorkConnected()) {
      Util.showNoNet();
      return;
    }
    parValue = moneyNumEt.getText().toString().trim();
    lowestNum = moneyLimitEt.getText().toString().trim();
    pushCount = pushCountEt.getText().toString().trim();
    limitCount = limitCountEt.getText().toString().trim();
    if (startTime == -1) {
      Util.show("请选择生效时间");
      return;
    }
    if (overTime == -1) {
      Util.show("请选择失效时间");
      return;
    }
    if (Util.isNull(parValue)) {
      Util.show("请输入优惠金额");
      return;
    }
    if (Util.isNull(lowestNum)) {
      Util.show("请输入金额限制");
      return;
    }
    if (Util.isNull(pushCount)) {
      Util.show("请输入发布数量");
      return;
    }
    if (Util.isNull(limitCount)) {
      Util.show("请输入限领数量");
      return;
    }

    createCoupon();
  }


  private void createCoupon() {
    String url = WebAPI.coupons_create_post;
    final JSONObject json = new JSONObject();
    try {
      json.put("startTime", startTime);
      json.put("endTime", overTime);
      json.put("parValue", parValue);
      json.put("lowestConsumption", lowestNum);
      json.put("quantity", pushCount);
      json.put("limitPerOneQuantity", limitCount);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    AnimaUtil.showLoading(context);
    final Map<String, Object> map = new HashMap<>();
    map.put("dto", json);
    String token = UserData.getUser() == null ? "" : UserData.getUser().getToken();
    map.put("token", token);
    Web.postJsonOk(url, map, new NetCallBack(response -> {
      AnimaUtil.stopLoading();
      if (NetUtils.SUCCESS != response.statusCode) {
        if (!Util.isNull(response.errorMsg)) {
          Util.show(response.errorMsg);
          return;
        }
        Util.showNetError();
        return;
      }
      String id = DataUtil.getJsonString(response.result, "identifier");
      Intent intent = new Intent(context, CouponCreateSuccessActivity.class);
      intent.putExtra("startTime", startTime);
      intent.putExtra("overTime", overTime);
      intent.putExtra("moneyNum", parValue);
      intent.putExtra("moneyLimit", lowestNum);
      intent.putExtra("pushCount", pushCount);
      intent.putExtra("limitCount", limitCount);
      intent.putExtra("isCreate", true);
      intent.putExtra("id", id);
      startActivity(intent);
      finish();

    }));
  }

  private void requestFocus(EditText et) {
    et.setFocusable(true);
    et.setFocusableInTouchMode(true);
    et.requestFocus();
  }
}
